#!/bin/bash

#Copyright (c) Beijing Wansheng Intelligent Corp. All rights reserved.
#Licensed under the MIT license. See LICENSE file in the project root for full license information.


script_path=$(cd "$(dirname "$0")/" && pwd)
build_dir=$script_path/build
samples_dir=$(readlink -f "$script_path/..")

if [ "$1" = "help" ] || [ "$1" = "-h" ]; then
    echo "./build_hello_mains.sh [run]"
    exit 0
fi

if [ -z "$WA_SDK_DIR" ]; then
    [ -d "$samples_dir/../out/host/wa-iot" ] && export WA_SDK_DIR="$samples_dir/../out/host/wa-iot"
    # set for distribution
    [ -d "$samples_dir/../wa-iot-sdk/host" ] && export WA_SDK_DIR="$samples_dir/../wa-iot-sdk/host"
fi

if [ -z "$WA_SDK_DIR" ]; then
    echo "Please set WA_SDK_DIR to the path of WA-SDK toolchains, exit.." && exit 1
else
    [ ! -d $WA_SDK_DIR ] && echo "WA_SDK_DIR $WA_SDK_DIR not present, exit.." && exit 1
fi

[ ! -f $WA_SDK_DIR/wa-sdk.cmake ] && echo "No wa-sdk.cmake file under WA_SDK_DIR [$WA_SDK_DIR]. exit.." && exit 1

CAMKE_WA_SDK_DIR="-DWA_SDK_DIR=$WA_SDK_DIR"
echo "WA_SDK_DIR=$WA_SDK_DIR"

$samples_dir/plugin-hello/build_hello.sh
[ $? -eq 0 ] || exit $?

[ -d $build_dir ] && rm -rf $build_dir
mkdir -p $build_dir
cd $build_dir
cmake .. -DCMAKE_BUILD_TYPE=Debug $CAMKE_WA_SDK_DIR -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=$build_dir/bin 
[ $? -eq 0 ] || exit $?
make
[ $? -eq 0 ] || exit $?

cp ../src/hello_world_lin.json $build_dir/bin 
cp $samples_dir/plugin-hello/build/bin/* $build_dir/bin

if [ "$1" = "run" ]; then
    ln -sf $samples_dir/plugin-hello/out/bin/libhello_world_client.so $build_dir/bin/libhello_world_client.so
    ln -sf $samples_dir/plugin-hello/out/bin/libhello_world_service.so $build_dir/bin/libhello_world_service.so
    if [ ! -f $build_dir/bin/libhello_world_client.so ]; then
        echo "libhello_world_client.so not found"
        echo "Please build plugin-hello first"
        echo "cd $samples_dir/plugin-hello; ./build_hello.sh"
        exit 1
    fi
    if [ ! -f $build_dir/bin/libhello_world_service.so ]; then
        echo "libhello_world_service.so not found, exit.."
        exit 1
    fi

    cd $build_dir/bin 
    LD_LIBRARY_PATH=$WA_SDK_DIR/lib ./hello_world_sample hello_world_lin.json
    exit 0
else
    echo " "
    echo "build successful. run following command:"
    echo "cd build/bin; ./hello_world_sample hello_world_lin.json"
fi

